<html>

<head>
  <title>离线瓦片地图</title>
  <link rel="stylesheet" type="text/css" href="./ol.css">
  <script type="text/javascript" src="./ol.js" charset="utf-8"></script>

  <style>
    .map {
      width: 100%;
      height: 400px;
    }

    .ol-tooltip {
      position: relative;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 4px;
      color: white;
      padding: 4px 8px;
      opacity: 0.7;
      white-space: nowrap;
      font-size: 12px;
      cursor: default;
      user-select: none;
    }

    .ol-tooltip-measure {
      opacity: 1;
      font-weight: bold;
    }

    .ol-tooltip-static {
      background-color: #ffcc33;
      color: black;
      border: 1px solid white;
    }

    .ol-tooltip-measure:before,
    .ol-tooltip-static:before {
      border-top: 6px solid rgba(0, 0, 0, 0.5);
      border-right: 6px solid transparent;
      border-left: 6px solid transparent;
      content: "";
      position: absolute;
      bottom: -6px;
      margin-left: -7px;
      left: 50%;
    }

    .ol-tooltip-static:before {
      border-top-color: #ffcc33;
    }
  </style>
</head>

<body>
  <div id="map" class="map"></div>
  <form class="form-inline">
    <label for="type">Measurement type &nbsp;</label>
    <select id="type">
      <option value="length">Length (LineString)</option>
      <option value="area">Area (Polygon)</option>
    </select>
  </form>

  <script type="text/javascript">



    // 地图设置中心，设置到成都，在本地离线地图 offlineMapTiles刚好有一张zoom为4的成都瓦片
    var center = ol.proj.transform([104.06667, 30.66667], 'EPSG:4326', 'EPSG:3857');
    //var center = ol.proj.transform([104.06667, 30.66667], 'EPSG:4326', 'EPSG:3857');
    //创建地图
    var map = new ol.Map({
      view: new ol.View({
        center: center,
        projection: 'EPSG:3857',
        zoom: 7,
        maxZoom: 14,
        minZoom: 4
      }),
      target: 'map'
    });

    function zeroFill(num, len, radix) {
      var str = num.toString(radix || 10);
      while (str.length < len) {
        str = "0" + str;
      }
      return str;
    }
    // 添加一个使用离线瓦片地图的层
    var offlineMapLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'http://localhost:8080/gis/{z}/{x}/{y}.png'
        // url: 'http://localhost:8080/GoogleDX/{z}/{x}/{y}.png'
      })
    });
    map.addLayer(offlineMapLayer);



    const source = new ol.source.Vector();
    const vector = new ol.layer.Vector({
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.2)',
        }),
        stroke: new ol.style.Stroke({
          color: '#ffcc33',
          width: 2,
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#ffcc33',
          }),
        }),
      }),
    });
    map.addLayer(vector);


    /**
 * Currently drawn feature.
 * @type {import("../src/ol/Feature.js").default}
 */
    let sketch;

    /**
     * The help tooltip element.
     * @type {HTMLElement}
     */
    let helpTooltipElement;

    /**
     * Overlay to show the help messages.
     * @type {Overlay}
     */
    let helpTooltip;

    /**
     * The measure tooltip element.
     * @type {HTMLElement}
     */
    let measureTooltipElement;

    /**
     * Overlay to show the measurement.
     * @type {Overlay}
     */
    let measureTooltip;

    /**
     * Message to show when the user is drawing a polygon.
     * @type {string}
     */
    const continuePolygonMsg = 'Click to continue drawing the polygon';

    /**
     * Message to show when the user is drawing a line.
     * @type {string}
     */
    const continueLineMsg = '点击继续画线';


    /**
 * Handle pointer move.
 * @param {import("../src/ol/MapBrowserEvent").default} evt The event.
 * 看起来应该是用于画线
 */
    const pointerMoveHandler = function (evt) {
      if (evt.dragging) {
        return;
      }
      /** @type {string} */
      let helpMsg = '点击开始绘制';

      if (sketch) {
        const geom = sketch.getGeometry();
        if (geom instanceof ol.geom.Polygon) {
          helpMsg = continuePolygonMsg;
        } else if (geom instanceof ol.geom.LineString) {
          helpMsg = continueLineMsg;
        }
      }

      helpTooltipElement.innerHTML = helpMsg;
      helpTooltip.setPosition(evt.coordinate);

      helpTooltipElement.classList.remove('hidden');
      console.log("完成了111")
    };

    map.on('pointermove', pointerMoveHandler);
    map.getViewport().addEventListener('mouseout', function () {
      helpTooltipElement.classList.add('hidden');
    });

    const typeSelect = document.getElementById('type');

    let draw; // global so we can remove it later

    /**
     * Format length output.
     * @param {LineString} line The line.
     * @return {string} The formatted length.
     * 用于转换米千米
     */
    const formatLength = function (line) {
      const length = ol.sphere.getLength(line);
      let output;
      if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
      } else {
        output = Math.round(length * 100) / 100 + ' ' + 'm';
      }
      return output;
    };


    /**
 * Format area output.
 * @param {Polygon} polygon The polygon.
 * @return {string} Formatted area.
 * 平方米千米
 */
    const formatArea = function (polygon) {
      const area = ol.sphere.getArea(polygon);
      let output;
      if (area > 10000) {
        output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
      } else {
        output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
      }
      return output;
    };



    function addInteraction() {
      console.log("执行了")
     // const type = typeSelect.value == 'area' ? 'Polygon' : 'LineString';
      draw = new ol.interaction.Draw({
        source: source,
        // type: type,
        type: "LineString",
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)',
          }),
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 0, 0.5)',
            lineDash: [10, 10],
            width: 2,
          }),
          image: new ol.style.Circle({
            radius: 5,
            stroke: new ol.style.Stroke({
              color: 'rgba(0, 0, 0, 0.7)',
            }),
            fill: new ol.style.Fill({
              color: 'rgba(255, 255, 255, 0.2)',
            }),
          }),
        }),
      });
      map.addInteraction(draw);

      createMeasureTooltip();
      createHelpTooltip();

      let listener;
      draw.on('drawstart', function (evt) {
        // set sketch
        sketch = evt.feature;

        /** @type {import("../src/ol/coordinate.js").Coordinate|undefined} */
        let tooltipCoord = evt.coordinate;

        listener = sketch.getGeometry().on('change', function (evt) {
          const geom = evt.target;
          let output;
          if (geom instanceof ol.geom.Polygon) {
            output = formatArea(geom);
            tooltipCoord = geom.getInteriorPoint().getCoordinates();
          } else if (geom instanceof ol.geom.LineString) {
            output = formatLength(geom);
            tooltipCoord = geom.getLastCoordinate();
          }
          measureTooltipElement.innerHTML = output;
          measureTooltip.setPosition(tooltipCoord);
        });
        console.log("开始画了")
      });

      draw.on('drawend', function () {
        measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
        measureTooltip.setOffset([0, -7]);
        // unset sketch
        sketch = null;
        // unset tooltip so that a new one can be created
        measureTooltipElement = null;
        //createMeasureTooltip();
        ol.Observable.unByKey(listener);
        console.log("画结束了")
        map.removeInteraction(draw);
        map.removeOverlay(helpTooltip);
      });
    }


    /**
 * Creates a new help tooltip
 */
    function createHelpTooltip() {
      if (helpTooltipElement) {
        helpTooltipElement.parentNode.removeChild(helpTooltipElement);
      }
      helpTooltipElement = document.createElement('div');
      helpTooltipElement.className = 'ol-tooltip hidden';
      helpTooltip = new ol.Overlay({
        element: helpTooltipElement,
        offset: [15, 0],
        positioning: 'center-left',
      });
      map.addOverlay(helpTooltip);
    }

    /**
     * Creates a new measure tooltip
     */
    function createMeasureTooltip() {
      if (measureTooltipElement) {
        measureTooltipElement.parentNode.removeChild(measureTooltipElement);
      }
      measureTooltipElement = document.createElement('div');
      measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
      measureTooltip = new ol.Overlay({
        element: measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
        stopEvent: false,
        insertFirst: false,
      });
      map.addOverlay(measureTooltip);
    }

    /**
     * Let user change the geometry type.
     */
    typeSelect.onchange = function () {
      map.removeInteraction(draw);
      addInteraction();
    };

    addInteraction();
  </script>

</body>

</html>